<template>
  <view class="container">
    <!-- 地址提示 -->
    <view class="address-tip">
      <view style="width: 100rpx">
        <u-icon name="map" size="30"></u-icon>
      </view>
      block
      <view>
        <view
        @click="setAddress()"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <text class="tip-text">暂无收货地址</text>
          <u-icon name="arrow-right" ></u-icon>
        </view>
        <text class="tip-desc">（请详细填写本人收货地址，如xx小区x栋xx）</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="orderInfo">
      <image
        style="width: 185rpx; height: 166rpx; margin-right: 10rpx"
        :src="dataClass.mainImage"
        mode="aspectFill"
      ></image>
      <view class="info">
        <view class="infoname">
          <view class="tag">品牌</view>
          <view class="name">{{ dataClass.productName || "保密中" }}</view>
        </view>
        <view class="Specifications"
          >规格：{{ dataClass.specifications || "" }}</view
        >
        <view class="Specifications">数量：{{ forRef.num }}</view>
        <view class="price">￥{{ forRef.numberSum }}</view>
      </view>
    </view>

    <!-- 租赁参数 -->
    <view class="rental-info">
      <view class="item">
        <text class="label">租期</text>
        <text class="value">{{ forRef.tenancy }}天</text>
      </view>
      <view class="item">
        <text class="label">日租价</text>
        <text class="value">￥{{ dailyPrice }}/天</text>
      </view>
      <view class="item">
        <text class="label">租金付款方式</text>
        <text class="value">{{ textRef }}</text>
      </view>
    </view>

    <!-- 个人信息 -->
    <view class="info-section">
      <view class="section-title">请完善你的个人信息</view>

      <view class="df-ac">
        <text>姓名</text>
        <view style="width: 500rpx">
          <u--input
            border="none"
            @input="validateName"
            v-model="formData.name"
            placeholder="请输入姓名"
            class="input-item"
          />
          <text v-if="nameError" class="error-text">{{ nameError }}</text>
        </view>
      </view>
      <view class="df-ac">
        <text>身份证</text>
        <view style="width: 500rpx">
          <u--input
            border="none"
            @input="validateIdCard"
            v-model="formData.idCard"
            placeholder="请输入身份证号码"
            class="input-item"
          />
          <text v-if="idCardError" class="error-text">{{ idCardError }}</text>
        </view>
      </view>

      <view style="border-bottom: 2px solid #eee" />

      <view class="id-upload">
        <view>请上传身份证正反面</view>
        <view class="upload-item">
          <view class="">
            <text class="upload-label">头像面</text>
            <text class="upload-span">上传您的身份证头像面</text>
          </view>
          <view class="">
            <u-upload :action="action" :file-list="fileList">
              <template>
                <image
                  src="/static/mine/Framezx.png"
                  style="width: 169.39px; height: 92.83px"
                ></image>
              </template>
            </u-upload>
          </view>
        </view>
        <view class="upload-item">
          <view class="">
            <text class="upload-label">国徽面</text>
            <text class="upload-span">上传您的身份证国徽面</text>
          </view>
          <view class="">
            <u-upload :action="action" :file-list="fileList">
              <template>
                <image
                  src="/static/mine/Framefx.png"
                  style="width: 169.39px; height: 92.83px"
                ></image>
              </template>
            </u-upload>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作 -->
    <view class="footer">
      <view class="checkbox">
        <u-checkbox-group
          value="checked"
          placement="row"
          @change="checkboxChange"
        >
          <u-checkbox shape="circle"></u-checkbox>
        </u-checkbox-group>

        <text class="agree-text">
          我已阅读并同意签署
          <span style="color: #1677ff">"租赁服务协议及相关"</span>
        </text>
      </view>
      <view class="total-button">
        <view class="total">总计：￥{{ forRef.numberSum }}</view>
        <button class="submit-btn" @click="canOrder()">确认下单</button>
      </view>
    </view>

    <!-- </u-popup> -->
    <u-popup mode="bottom" :show="addressShow" :round="15">
      <view>
        <view class="addressContent">
            
            <!-- 填写地址 -->
          <addRess @index-class="address"></addRess>
          <!-- 填写地址 -->
          
         <view class="radio-button1">
            
            <button style="background-color: #1677ff;color: #ebf3ff;margin-left: 20rpx;" @click="addressConfirm()">
              确认
            </button>
            <button @click="addressClose()">取消</button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import addRess from "../../components/address/index.vue";
import api from "@/api/index.js";
import main from "@/api/main.js";
import { idCardValidate } from "@/utils/validate.js";
export default {
  components: {
    addRess,
  },
  data() {
    return {
      addressShow: false,
      dailyPrice: 0,
      checked: false,
      textRef: "支付宝",
      indexClass: {}, //地址
      forRef: {},
      dataClass: {},
      formData: {
        name: "",
        idCard: "",
      },
      nameError: "",
      idCardError: "",
    };
  },
  onLoad(e) {
    if (e.forRef) {
      const forRefInfo = JSON.parse(decodeURIComponent(e.forRef));
      console.log("yqttrqr", forRefInfo.id);
      this.getIdClass(forRefInfo.id);
      this.forRef = forRefInfo;
    }
    this.getOrderList();
  },
  computed: {
    isFormValid() {
      return (
        !this.nameError &&
        !this.idCardError &&
        this.formData.name &&
        this.formData.idCard
      );
    },
  },
  methods: {
    address(row) {
        console.log("row222",row);
      this.indexClass = row;
    },
    checkboxChange() {
      this.checked = !this.checked;
    },
    //验证
    // 姓名验证（2-4个中文字符）
    validateName() {
      const value = this.formData.name.trim();
      const regex = /^[\u4e00-\u9fa5]{2,4}$/;

      if (!value) {
        this.nameError = "姓名不能为空";
      } else if (!regex.test(value)) {
        this.nameError = "请输入2-4个中文字符";
      } else {
        this.nameError = "";
      }
    },
    validateIdCard() {
      const value = this.formData.idCard.trim();
      if (!value) {
        this.idCardError = "身份证不能为空";
      } else if (!idCardValidate(value)) {
        this.idCardError = "身份证输入有误，请重新输入";
      } else {
        this.idCardError = "";
      }
    },
    handleUpload(type) {
      console.log("上传类型:", type);
    },
    setAddress() {
      this.addressShow = true;
    },
    addressClose() {
      this.addressShow = false;
    },
    addressConfirm() {
      this.addressShow = false;
    },
    
    //创建订单
    canOrder() {
      if (!this.checked) {
        uni.showToast({
          title: "请勾选协议后在继续",
          icon: "none", // 可选 success/loading/none
          duration: 2000, // 持续时间，单位ms
        });
        return;
      }
      if(!this.formData.idCard){
          uni.showModal({
          	title: '温馨提醒',
          	content: '上传身份信息将提高免押额度哦～',
            showCancel:false,
          	success: function (res) {
          		if (res.confirm) {
          			console.log('我知道了');
          		} 
          	}
          });
      }
      

      // if (!this.isFormValid) {
      // 	this.validateName();
      // 	this.validateIdCard();
      // 	//TODO 身份验证后续操作
      // 	uni.showToast({
      // 		title: '请输入身份信息',
      // 		icon: 'none', // 可选 success/loading/none
      // 		duration: 2000 // 持续时间，单位ms
      // 	});
      // 	return;
      // }

      main
        .setOrder({
          // productSkuId: this.dataClass.leaseGoodSkus[0].id, //商品ID
          productSkuId: 1, //商品ID
          mainImage: "https://loremflickr.com/400/400?lock=3106705713449653",
          quantity: this.forRef.num, //数量
          rentalPeriod: this.forRef.tenancy, //天数
          paymentMethod: this.textRef, //租金付款方式
          productName: this.dataClass.productName, //商品名
          specifications: this.dataClass.specifications, //规格
          consignee: "政府和", //收货人
          consigneePhone: "17373908792", //收货手机号
          consigneeAddr: "武汉", //收货地址
          // deliveryMethod: this.forRef.chmod, //配送方式
          // amount: this.dataSum, //金额
          // totalAmount: this.forRef.numberSum //总金额
        })
        .then((data) => {
          if (data.code == 200) {
            uni.showToast({
              title: "下单成功",
              icon: "success", // 可选 success/loading/none
              duration: 2000, // 持续时间，单位ms
            });
            this.setPay(data.msg);
          }
        })
        .catch((erro) => {
          console.log(erro);
        });
    },
    setPay(id) {
      console.log("qwqwqwq", id);
      main
        .setPay(id)
        .then((data) => {
          console.log("dataqqqqqqqqqqqqqqqqtat", data);
          if (data.code == 200) {
            let outTradeNo = data.outTradeNo;
            let tradeNo = data.tradeNo;
            // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号 trade_no

            my.tradePay({
              tradeNO: tradeNo,
              success: (res) => {
                uni.reLaunch({
                  url: "/subPages/mine/allOrder",
                });
              },
              fail: (error) => {
                console.error("调用 my.tradePay 失败: ", JSON.stringify(error));
              },
            });
          }
        })
        .catch((erro) => {
          console.log(erro);
        });
    },
    getIdClass(id) {
      main
        .getIdClass(id)
        .then((data) => {
          console.log("asasas", data);
          this.dataClass = data.data;
          this.dailyPrice =
            (this.dataClass &&
              this.dataClass.leaseGoodSkus &&
              this.dataClass.leaseGoodSkus[0] &&
              this.dataClass.leaseGoodSkus[0].leaseRentalRules &&
              this.dataClass.leaseGoodSkus[0].leaseRentalRules[0]
                ?.everydayPrice) ||
            5;
        })
        .catch((erro) => {
          console.log(erro);
        });
    },
    getOrderList() {
      main
        .getOrderList({
          pageNo: 1,
          pageSize: 30,
        })
        .then((data) => {
          console.log("as----------asas", data);
        })
        .catch((erro) => {
          console.log(erro);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.error-text {
  color: #ff4545;
  font-size: 24rpx;
  margin-top: 10rpx;
}
.container {
  padding-bottom: 20rpx;
  background-color: #eee;
  height: calc(100vh + 200rpx);

  .orderInfo {
    box-sizing: border-box;
    display: flex;
    background-color: #fff;
    margin: 30rpx;
    padding: 25rpx;
    border-radius: 10rpx;

    .info {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
    }

    .infoname {
      display: flex;
      align-items: center;

      .tag {
        width: 64rpx;
        height: 36rpx;
        line-height: 36rpx;
        text-align: center;
        color: #1677ff;
        background-color: #deecff;
        border-radius: 25px;
        font-size: 20rpx;
        margin-right: 8rpx;
      }

      .name {
        font-size: 28rpx;
      }

      .mode {
        width: 64rpx;
        height: 36rpx;
        line-height: 36rpx;
        text-align: center;
        color: #ff8662;
        border: 1px solid #ff8662;
        border-radius: 3px;
        font-size: 20rpx;
        margin-left: 15rpx;
      }
    }

    .Specifications {
      color: #777;
      font-size: 24rpx;
    }

    .price {
      font-size: 30x;
      color: red;
      font-weight: 600;
    }
  }
  .address-tip {
    margin-top: 20rpx;
    padding: 30rpx;
    background: #fff;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    margin: 20rpx;
    .tip-text {
      margin: 0 20rpx;
      font-size: 32rpx;
    }
    .tip-desc {
      display: block;
      margin-top: 15rpx;
      font-size: 26rpx;
      color: red;
    }
  }
}

.rental-info {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 10rpx;
  .item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
  }
}

.info-section {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 10rpx;

  .df-ac {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
  }
  .input-item {
    margin-bottom: 30rpx;
  }
  .section-title {
    font-size: 34rpx;
    color: #333;
    margin-bottom: 30rpx;
  }

  .id-upload {
    margin: 30rpx 0 30vh 0;
    display: flex;
    flex-direction: column;
    gap: 30rpx;

    .upload-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .upload-label {
      display: block;
      color: #666;
    }
    .upload-span {
      color: #a6a6a6;
      font-size: 23rpx;
    }
  }
}

.footer {
  padding: 30rpx;
  background: #fff;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 150rpx;
  box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.1);
  .checkbox {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .agree-text {
      color: #666;
      margin-left: 20rpx;
    }
  }

  .total-button {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 50rpx;
    .total {
      font-size: 36rpx;
      color: #ff3b30;
      font-weight: bold;
      text-align: right;
      margin-bottom: 30rpx;
    }
    .submit-btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 34rpx;
      background-color: #1677ff;
      border-radius: 50rpx;
      color: #fff;
    }
  }
}
</style>
